package fr.emse.tatiana.importexport;


import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;

import fr.emse.tatiana.TatianaConfig;
import fr.emse.tatiana.TatianaConstants;
import fr.emse.tatiana.corpus.Corpus;

public  class ExportCorpusWizardMainPage extends WizardPage implements Listener{

	private ResourceTreeAndListGroup resourceGroup;
	IProject selection;
	private Combo destinationNameField;
	private Text nameNameField;
	private Button destinationBrowseButton;
	protected static final int SIZING_TEXT_FIELD_WIDTH = 250;
	private static final String SELECT_DESTINATION_MESSAGE = "Select destination for export";
	private static final String SELECT_DESTINATION_TITLE = "Select folder";

	protected ExportCorpusWizardMainPage(IProject selection2) {
		super("page1");
		setTitle("Export Corpus");
		setDescription("Choose the files which you would like to include in the export");
		this.selection=selection2;
	}


	public void createControl(Composite parent) {
		initializeDialogUnits(parent);

		Composite composite = new Composite(parent, SWT.NULL);
		composite.setLayout(new GridLayout());
		composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL
				| GridData.HORIZONTAL_ALIGN_FILL));
		composite.setFont(parent.getFont());

		createResourcesGroup(composite);

		createDestinationGroup(composite);

		createNameGroup(composite);


		/*restoreResourceSpecificationWidgetValues(); // ie.- local
	        restoreWidgetValues(); // ie.- subclass hook
	        if (initialResourceSelection != null) {
				setupBasedOnInitialSelections();
			}

	        updateWidgetEnablements();
	        setPageComplete(determinePageCompletion());
	        setErrorMessage(null);	// should not initially have error message
		 */
		setControl(composite);
	}
	private void createNameGroup(Composite parent) {
		Font font = parent.getFont();
		// destination specification group
		Composite destinationSelectionGroup = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		destinationSelectionGroup.setLayout(layout);
		destinationSelectionGroup.setLayoutData(new GridData(
				GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
		destinationSelectionGroup.setFont(font);

		Label destinationLabel = new Label(destinationSelectionGroup, SWT.NONE);
		destinationLabel.setText("Save as");
		destinationLabel.setFont(font);

		// destination name entry field
		nameNameField = new Text(destinationSelectionGroup, SWT.SINGLE
				| SWT.BORDER);
		nameNameField.addListener(SWT.Modify, this);
		nameNameField.addListener(SWT.Selection, this);
		GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL
				| GridData.GRAB_HORIZONTAL);
		data.widthHint = SIZING_TEXT_FIELD_WIDTH;
		nameNameField.setLayoutData(data);
		nameNameField.setFont(font);
		nameNameField.setText(selection.getName());

		new Label(parent, SWT.NONE); // vertical spacer
	}




	protected  void createResourcesGroup(Composite parent) {

		//create the input element, which has the root resource
		//as its only child

		StructuredSelection selec1= new StructuredSelection (selection);
		List selectedResources = IDE.computeSelectedResources(selec1);
		this.resourceGroup = new ResourceTreeAndListGroup(parent,selectedResources,
				getResourceProvider(IResource.FOLDER | IResource.PROJECT),
				WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider(),
				getResourceProvider(IResource.FILE), WorkbenchLabelProvider
				.getDecoratingWorkbenchLabelProvider(), SWT.NONE,
				false);

		/*
	        ICheckStateListener listener = new ICheckStateListener() {
	            public void checkStateChanged(CheckStateChangedEvent event) {
	                updateWidgetEnablements();
	            }
	        };

	        this.resourceGroup.addCheckStateListener(listener);*/
	}

	/*
	protected void updateWidgetEnablements() {
		boolean pageComplete = determinePageCompletion();
        setPageComplete(pageComplete);
        if (pageComplete) {
			setMessage(null);
		}
        super.updateWidgetEnablements();
    }*/

	
	private ITreeContentProvider getResourceProvider(final int resourceType) {
		return new WorkbenchContentProvider() {
			public Object[] getChildren(Object o) {
				if (o instanceof IContainer) {
					IResource[] members = null;
					try {
						members = ((IContainer) o).members();
					} catch (CoreException e) {
						//just return an empty set of children
						return new Object[0];
					}

					//filter out the desired resource types
					ArrayList results = new ArrayList();
					for (int i = 0; i < members.length; i++) {
						//And the test bits with the resource types to see if they are what we want
						if ((members[i].getType() & resourceType) > 0) {
							if (members[i].getName().startsWith(".") ||
									members[i].getName().equalsIgnoreCase("CVS") ||
									members[i].getName().equalsIgnoreCase("SVN") ||
									members[i].getName().equalsIgnoreCase(TatianaConstants.CACHE_FOLDER_NAME))
								continue;
							results.add(members[i]);
						}
					}
					
					return results.toArray();
				} 
				//input element case
				if (o instanceof ArrayList) {
					return ((ArrayList) o).toArray();
				} 
				return new Object[0];
			}
		};
	}


	
	
	protected void setDestinationValue(String value) {
		destinationNameField.setText(value);
	}
	protected String getDestinationValue() {
        return destinationNameField.getText().trim();
    }
	
	public void handleDestinationBrowseButtonPressed() {
		DirectoryDialog dialog = new DirectoryDialog(getContainer().getShell(),
				SWT.SAVE);
		dialog.setMessage(SELECT_DESTINATION_MESSAGE);
		dialog.setText(SELECT_DESTINATION_TITLE);
		dialog.setFilterPath(getDestinationValue());
		String selectedDirectoryName = dialog.open();

		if (selectedDirectoryName != null) {
			setErrorMessage(null);
			setDestinationValue(selectedDirectoryName);
		}

	}

	public void handleEvent(Event e) {
		Widget source = e.widget;

		if (source == destinationBrowseButton) {
			handleDestinationBrowseButtonPressed();
		}
		((ExportCorpusWizard) getWizard()).setPath(destinationNameField.getText());
		((ExportCorpusWizard) getWizard()).setFileName(nameNameField.getText());
		
		updatePageCompletion();
	}

	protected void createDestinationGroup(Composite parent) {
		Font font = parent.getFont();
		// destination specification group
		Composite destinationSelectionGroup = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		destinationSelectionGroup.setLayout(layout);
		destinationSelectionGroup.setLayoutData(new GridData(
				GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
		destinationSelectionGroup.setFont(font);

		Label destinationLabel = new Label(destinationSelectionGroup, SWT.NONE);
		destinationLabel.setText("Export to Folder");
		destinationLabel.setFont(font);

		// destination name entry field
		destinationNameField = new Combo(destinationSelectionGroup, SWT.SINGLE
				| SWT.BORDER);
		destinationNameField.addListener(SWT.Modify, this);
		destinationNameField.addListener(SWT.Selection, this);
		GridData data = new GridData(GridData.HORIZONTAL_ALIGN_FILL
				| GridData.GRAB_HORIZONTAL);
		data.widthHint = SIZING_TEXT_FIELD_WIDTH;
		destinationNameField.setLayoutData(data);
		destinationNameField.setFont(font);

		// destination browse button
		destinationBrowseButton = new Button(destinationSelectionGroup,
				SWT.PUSH);
		destinationBrowseButton.setText("Browse...");
		destinationBrowseButton.addListener(SWT.Selection, this);
		destinationBrowseButton.setFont(font);
		setButtonLayoutData(destinationBrowseButton);

		new Label(parent, SWT.NONE); // vertical spacer
	}


	protected void updatePageCompletion() {
		boolean pageComplete = determinePageCompletion();
		setPageComplete(pageComplete);
		if (pageComplete) {
			setErrorMessage(null);
		}
	}
	protected boolean determinePageCompletion() {
		boolean complete = validateSourceGroup() && validateDestinationGroup();

		if (complete) {
			setErrorMessage(null);
		}

		return complete;
	}
	protected boolean validateDestinationGroup() {
		if(destinationNameField.getText().equals("")){
			return false;
		}
		if(nameNameField.getText().equals("")){
			return false;
		}
		return true;
	}
	protected boolean validateSourceGroup() {
		return true;
	}

	public  List getWhiteCheckedResources() {
		List l = resourceGroup.getAllWhiteCheckedItems();
		List ret = new Vector();
		for (Object f: l) {
			if (f instanceof IResource && ((IResource)f).getName().startsWith(".")) {
				continue;
			}
			ret.add(f);
			if (f instanceof IFile) {
				IFile file = (IFile) f;
				ret.addAll(Corpus.getAssociatedHiddenFiles(file));
			}
		}
        return ret;
    }


	public  boolean finish(String string) {

		List list= getWhiteCheckedResources();
		
	    return executeExportOperation(new ArchiveFileExportOperation(null,list,string));
	}

	protected boolean executeExportOperation(ArchiveFileExportOperation op) {
        op.setCreateLeadupStructure(true);
        op.setUseCompression(true);
        op.setUseTarFormat(false);
        try {
			op.run(null);
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


        
       // IStatus status = op.getStatus();
       // if (!status.isOK()) {
          ////  ErrorDialog.openError(getContainer().getShell(),
          //          DataTransferMessages.DataTransfer_exportProblems,
          //          null, // no special message
          //          status);
        //	System.out.println("Status not OK");
        //    return false;
        //}
        return true;
    }
	
}
